import axios from "axios";
import config from '../config';
import { ElMessage } from "element-plus";

//axios实例对象
const service = axios.create({
    baseURL: config.baseApi
})

//请求之前
service.interceptors.request.use((req) => {
    return req
})

//请求之后
service.interceptors.response.use((res) => {
    const { code, data, msg } = res.data
    //根据后端需求
    if (code == 200) {
        return data
    } else {
        //网络请求错误
        ElMessage.error(msg || '网络异常，稍后重试')
        return Promise.reject(msg || '网络异常，稍后重试')
    }
})

//封装的核心函数
function request(options) {
    options.method = options.method || 'get'
    if (options.method.toLowerCase() == 'get') {
        options.params = options.data
    }
    //对mock的处理
    let isMock = config.mock
    if (typeof options.mock !== 'undefined') {
        isMock = options.mock
    }
    //对线上环境处理
    if (config.env == 'prod') {
        //不允许使用mock
        service.defaults.baseURL = config.baseApi
    } else {
        service.defaults.baseURL = isMock ? config.mockApi : config.baseApi
    }
    return service(options)
}

export default request